﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.DAL;
using WXYW.Entities;
using WXYW.Model;

namespace WXYW.BLL
{
    public class AccessoryService : RepositoryBase
    {
        public IQueryable<Accessory> GetAccessory(string str)
        {
            return GetEntities<Accessory>(a => a.ModelNO.Contains(str));
        }

        public Accessory GetAccessoryByName(string name)
        {
            return GetEntities<Accessory>(a => a.ModelNO == name).FirstOrDefault();
        }

        public Accessory GetAccessoryByName(string name, int stationID)
        {
            return GetEntities<Accessory>(a => a.ModelNO == name && a.ServiceStation.ID == stationID).FirstOrDefault();
        }

        public Accessory GetAccessoryByID(int accessoryID)
        {
            return GetEntities<Accessory>(a=>a.ID == accessoryID).FirstOrDefault();
        }

        public IQueryable<AccessoryClass> GetAccessoryTypeList()
        {
            return GetEntities<AccessoryClass>();
        }

        public List<AccessoryModel> GetAccessoryList(string keywrod)
        {
            List<AccessoryModel> accessoryModels = new List<AccessoryModel>();
            IQueryable<Accessory> accessoryEntities = GetEntities<Accessory>();
            if (!string.IsNullOrEmpty(keywrod))
            {
                accessoryEntities = accessoryEntities.Where(a => a.AccessoryClass.Name.Contains(keywrod) 
                    || a.Description.Contains(keywrod) || a.MaterialNO.Contains(keywrod) || a.ModelNO.Contains(keywrod) 
                    || a.ServiceStation.Name.Contains(keywrod));

            }
            foreach (Accessory accessoryEntity in accessoryEntities)
            {
                AccessoryModel accessoryModel = new AccessoryModel();
                if (!accessoryEntity.AccessoryClassReference.IsLoaded)
                {
                    accessoryEntity.AccessoryClassReference.Load();
                }
                accessoryModel.Class = accessoryEntity.AccessoryClass.Name;
                accessoryModel.Description = accessoryEntity.Description;
                accessoryModel.ID = accessoryEntity.ID.ToString();
                accessoryModel.MaterialNO = accessoryEntity.MaterialNO;
                accessoryModel.ModelNO = accessoryEntity.ModelNO;
                accessoryModel.Price = accessoryEntity.Price.ToString();
                accessoryModel.CHPrice = accessoryEntity.CBPrice.HasValue ? accessoryEntity.CBPrice.Value.ToString() : "";
                accessoryModel.UseTimes = accessoryEntity.UseTimes.ToString();
                accessoryModel.Count = accessoryEntity.Count.ToString();
                if (!accessoryEntity.ServiceStationReference.IsLoaded)
                {
                    accessoryEntity.ServiceStationReference.Load();
                }
                accessoryModel.Station = accessoryEntity.ServiceStation.Name;
                accessoryModels.Add(accessoryModel);
            }
            return accessoryModels;
        }

        public void AddAccessory(string materialNO, string modelNO, string description, decimal price, int count,
           int classID, int stationID, User currentOperator)
        {
            Accessory accessoryEntity = GetEntities<Accessory>().Where(a => a.ModelNO.Equals(modelNO) && a.ServiceStation.ID == stationID).FirstOrDefault();
            if (accessoryEntity != null)
            {
                accessoryEntity.MaterialNO = materialNO;
                accessoryEntity.Count += count;
                //accessoryEntity.Price = price;
                //accessoryEntity.AccessoryClass = GetEntities<AccessoryClass>().Where(c => c.ID == classID).FirstOrDefault();
                //accessoryEntity.Description = description;
                accessoryEntity.LastUpdate = DateTime.Now;
                accessoryEntity.LastUpdateBy = currentOperator.UserID;
                UpdateEntity(accessoryEntity);
            }
            else
            {
                accessoryEntity = new Accessory();
                accessoryEntity.MaterialNO = materialNO;
                accessoryEntity.ModelNO = modelNO;
                accessoryEntity.Price = price;
                accessoryEntity.Count = count;
                accessoryEntity.AccessoryClass = GetEntities<AccessoryClass>().Where(c => c.ID == classID).FirstOrDefault();
                accessoryEntity.Description = description;
                accessoryEntity.LastUpdate = DateTime.Now;
                accessoryEntity.LastUpdateBy = currentOperator.UserID;
                accessoryEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == stationID).FirstOrDefault();
                InsertEntity(accessoryEntity);
            }

            AccessoryRecord recordEntity = new AccessoryRecord();
            recordEntity.EnterCount = count;
            recordEntity.EnterDate = DateTime.Now;
            recordEntity.ModelNumber = modelNO;
            recordEntity.OperationType = "新增";
            recordEntity.OperatorID = currentOperator.UserID;
            recordEntity.ServiceStation = GetEntities<ServiceStation>().Where(s => s.ID == stationID).FirstOrDefault();
            InsertEntity(recordEntity);
        }

        public void EditAccessory(string materialNO, string modelNO, string description, decimal price, int classID, int stationID, User currentOperator)
        {
            Accessory accessoryEntity = GetEntities<Accessory>().Where(a => a.ModelNO.Equals(modelNO) && a.ServiceStation.ID == stationID).FirstOrDefault();
            if (accessoryEntity != null)
            {
                accessoryEntity.MaterialNO = materialNO;
                accessoryEntity.Price = price;
                accessoryEntity.AccessoryClass = GetEntities<AccessoryClass>().Where(c => c.ID == classID).FirstOrDefault();
                accessoryEntity.Description = description;
                accessoryEntity.LastUpdate = DateTime.Now;
                accessoryEntity.LastUpdateBy = currentOperator.UserID;
                UpdateEntity(accessoryEntity);
            }
            else
            {
                throw new Exception("修改的元器件记录已经不存在");
            }
        }

        public void TransferAccessory(long accessoryID, int transferCount, string comment, int targetStationID, User currentOperator)
        {
            Accessory accessoryEntity = GetEntities<Accessory>().Where(a => a.ID == accessoryID).FirstOrDefault();
            accessoryEntity.Count -= transferCount;
            accessoryEntity.LastUpdate = DateTime.Now;
            accessoryEntity.LastUpdateBy = currentOperator.UserID;
            UpdateEntity(accessoryEntity);

            ServiceStation targetStation = GetEntities<ServiceStation>().Where(s => s.ID == targetStationID).FirstOrDefault();

            Accessory accessoryEntityInTargetStation = GetEntities<Accessory>().Where(a => a.ModelNO.Equals(accessoryEntity.ModelNO) && a.ServiceStation.ID == targetStationID).FirstOrDefault();
            if (accessoryEntityInTargetStation != null)
            {
                accessoryEntityInTargetStation.Count += transferCount;
                accessoryEntityInTargetStation.LastUpdate = DateTime.Now;
                accessoryEntityInTargetStation.LastUpdateBy = currentOperator.UserID;
                UpdateEntity(accessoryEntityInTargetStation);
            }
            else
            {
                accessoryEntityInTargetStation = new Accessory();
                accessoryEntityInTargetStation.Count = transferCount;
                if (!accessoryEntity.AccessoryClassReference.IsLoaded)
                {
                    accessoryEntity.AccessoryClassReference.Load();
                }
                accessoryEntityInTargetStation.AccessoryClass = accessoryEntity.AccessoryClass;
                accessoryEntityInTargetStation.CBPrice = accessoryEntity.CBPrice;
                accessoryEntityInTargetStation.Description = accessoryEntity.Description;
                accessoryEntityInTargetStation.LastUpdate = DateTime.Now;
                accessoryEntityInTargetStation.LastUpdateBy = currentOperator.UserID;
                accessoryEntityInTargetStation.MaterialNO = accessoryEntity.MaterialNO;
                accessoryEntityInTargetStation.ModelNO = accessoryEntity.ModelNO;
                accessoryEntityInTargetStation.Price = accessoryEntity.Price;
                accessoryEntityInTargetStation.ServiceStation = targetStation;
                accessoryEntityInTargetStation.UseTimes = accessoryEntity.UseTimes;
                InsertEntity(accessoryEntityInTargetStation);
            }

            AccessoryRecord sourceRecordEntity = new AccessoryRecord();
            sourceRecordEntity.Comment = comment;
            sourceRecordEntity.TransferCount = transferCount;
            sourceRecordEntity.TransferDate = DateTime.Now;
            sourceRecordEntity.ModelNumber = accessoryEntity.ModelNO;
            if (!accessoryEntity.ServiceStationReference.IsLoaded)
            {
                accessoryEntity.ServiceStationReference.Load();
            }
            sourceRecordEntity.ServiceStation = accessoryEntity.ServiceStation;
            sourceRecordEntity.OperationType = string.Format("{0}->{1}", accessoryEntity.ServiceStation.Name, targetStation.Name);
            sourceRecordEntity.OperatorID = currentOperator.UserID;
            InsertEntity(sourceRecordEntity);

            AccessoryRecord targetRecordEntity = new AccessoryRecord();
            targetRecordEntity.Comment = comment;
            targetRecordEntity.EnterCount = transferCount;
            targetRecordEntity.EnterDate = DateTime.Now;
            targetRecordEntity.ModelNumber = accessoryEntity.ModelNO;
            targetRecordEntity.OperationType = string.Format("{0}->{1}", accessoryEntity.ServiceStation.Name, targetStation.Name);
            targetRecordEntity.ServiceStation = targetStation;
            InsertEntity(targetRecordEntity);
        }

        public void UpdateAccessory(Accessory accessory)
        {
            UpdateEntity(accessory);
        }

        public List<AccessoryRecordModel> GetAccessoryRecords(int accessoryID)
        {
            Accessory accessory = GetEntities<Accessory>().Where(a => a.ID == accessoryID).FirstOrDefault();
            if (!accessory.ServiceStationReference.IsLoaded)
            {
                accessory.ServiceStationReference.Load();
            }
            IQueryable<AccessoryRecord> recordEntities = GetEntities<AccessoryRecord>().Where(a => a.ModelNumber.Equals(accessory.ModelNO) &&
                a.ServiceStation.ID == accessory.ServiceStation.ID);
            List<AccessoryRecordModel> models = new List<AccessoryRecordModel>();
            foreach (AccessoryRecord record in recordEntities)
            {
                AccessoryRecordModel model = new AccessoryRecordModel();
                model.Comment = record.Comment;
                model.EnterCount = record.EnterCount.HasValue ? record.EnterCount.Value.ToString() : "";
                model.EnterDate = record.EnterDate.HasValue ? record.EnterDate.Value.ToString("yyyy-MM-dd") : "";
                model.ModelNumber = record.ModelNumber;
                model.OperationType = record.OperationType;
                User userEntity = GetEntities<User>().Where(u => u.UserID == record.OperatorID.Value).FirstOrDefault();
                if (userEntity != null)
                {
                    //model.Operator = userEntity.UserName;
                    model.Operator = userEntity.ContactPerson;
                }
                model.TransferCount = record.TransferCount.HasValue ? record.TransferCount.Value.ToString() : "";
                model.TransferDate = record.TransferDate.HasValue ? record.TransferDate.Value.ToString("yyyy-MM-dd") : "";
                model.UseCount = record.UseCount.HasValue ? record.UseCount.Value.ToString() : "";
                model.UseDate = record.UseDate.HasValue ? record.UseDate.Value.ToString("yyyy-MM-dd") : "";
                models.Add(model);
            }
            return models;
        }

        public void TransferAccessoryOfPlatform(int accessoryID, int transferCount, string type, string comment , User currentOperator)
        {
            Accessory accessory = GetEntities<Accessory>().Where(a => a.ID == accessoryID).FirstOrDefault();
            accessory.Count -= transferCount;
            accessory.LastUpdate = DateTime.Now;
            accessory.LastUpdateBy = currentOperator.UserID;
            if (!accessory.ServiceStationReference.IsLoaded)
            {
                accessory.ServiceStationReference.Load();
            }
            UpdateEntity(accessory);

            if (type.Equals("-> 北京平台"))
            {
                Accessory accessoryInHeadPlatform = GetEntities<Accessory>().Where(a => a.ModelNO == accessory.ModelNO &&
                    a.ServiceStation.Name.Equals("北京平台")).FirstOrDefault();
                if (accessoryInHeadPlatform != null)
                {
                    accessoryInHeadPlatform.Count += transferCount;
                    accessoryInHeadPlatform.LastUpdate = DateTime.Now;
                    accessoryInHeadPlatform.LastUpdateBy = currentOperator.UserID;
                    UpdateEntity(accessoryInHeadPlatform);
                }
                else
                {
                    accessoryInHeadPlatform = new Accessory();
                    accessoryInHeadPlatform.Count += transferCount;
                    accessoryInHeadPlatform.LastUpdate = DateTime.Now;
                    accessoryInHeadPlatform.LastUpdateBy = currentOperator.UserID;
                    if (!accessory.AccessoryClassReference.IsLoaded)
                    {
                        accessory.AccessoryClassReference.Load();
                    }
                    accessoryInHeadPlatform.AccessoryClass = accessory.AccessoryClass;
                    accessoryInHeadPlatform.CBPrice = accessory.CBPrice;
                    accessoryInHeadPlatform.Count = transferCount;
                    accessoryInHeadPlatform.Description = accessory.Description;
                    accessoryInHeadPlatform.Price = accessory.Price;
                    accessoryInHeadPlatform.ModelNO = accessory.ModelNO;
                    accessoryInHeadPlatform.ServiceStation = GetEntities<ServiceStation>().Where(s => s.Name.Equals("北京平台")).FirstOrDefault();
                    InsertEntity(accessoryInHeadPlatform);
                }

                AccessoryRecord record = new AccessoryRecord();
                record.TransferDate = DateTime.Now;
                record.TransferCount = transferCount;
                record.OperatorID = currentOperator.UserID;
                record.ModelNumber = accessory.ModelNO;
                record.Comment = comment;
                record.ServiceStation = accessory.ServiceStation;
                record.OperationType = "-> 北京平台";
                InsertEntity(record);

                record = new AccessoryRecord();
                record.EnterDate = DateTime.Now;
                record.EnterCount = transferCount;
                record.OperatorID = currentOperator.UserID;
                record.ModelNumber = accessory.ModelNO;
                record.Comment = comment;
                record.ServiceStation = GetEntities<ServiceStation>().Where(s=>s.Name.Equals("北京平台")).FirstOrDefault();
                record.OperationType = string.Format("{0}->北京平台", accessory.ServiceStation.Name);
                InsertEntity(record);
            }
            else
            {
                AccessoryRecord record = new AccessoryRecord();
                record.UseDate = DateTime.Now;
                record.UseCount = transferCount;
                record.OperatorID = currentOperator.UserID;
                record.ModelNumber = accessory.ModelNO;
                record.Comment = comment;
                record.ServiceStation = accessory.ServiceStation;
                record.OperationType = "消耗";
                InsertEntity(record);
            }            
        }

        public void UseAccessoryInRepairProcess(int count, string modelNO, int stationID)
        {
            Accessory accessory = GetEntities<Accessory>().Where(a => a.ModelNO.Equals(modelNO) && a.ServiceStation.ID == stationID).FirstOrDefault();
            if (accessory != null)
            {
                accessory.Count -= count;
                accessory.LastUpdate = DateTime.Now;
                UpdateEntity(accessory);
                if (!accessory.ServiceStationReference.IsLoaded)
                {
                    accessory.ServiceStationReference.Load();
                }

                //增加使用记录
                AccessoryRecord useRecordEntity = new AccessoryRecord();
                useRecordEntity.UseCount = count;
                //useRecordEntity.EnterDate = DateTime.Now;
                useRecordEntity.UseDate = DateTime.Now;
                useRecordEntity.ModelNumber = modelNO;
                useRecordEntity.OperationType = string.Format("维修使用");
                useRecordEntity.ServiceStation = accessory.ServiceStation;
                InsertEntity(useRecordEntity);
            }
        }

        public List<AccessoryModel> QueryAccessory(string keyword, int stationID)
        {
            List<AccessoryModel> models = new List<AccessoryModel>();

            IQueryable<Accessory> entities = GetEntities<Accessory>();
            if (!string.IsNullOrEmpty(keyword))
            {
                entities = entities.Where(a => a.MaterialNO.Contains(keyword) || a.ModelNO.Contains(keyword) ||
                    a.Description.Contains(keyword) || a.AccessoryClass.Name.Contains(keyword));
            }
            
            if (stationID > 0)
            {
                entities = entities.Where(a=>a.ServiceStation.ID == stationID);
            }

            foreach(Accessory accessory in entities)
            {
                AccessoryModel model = new AccessoryModel();
                if (!accessory.AccessoryClassReference.IsLoaded)
                {
                    accessory.AccessoryClassReference.Load();
                }
                if (!accessory.ServiceStationReference.IsLoaded)
                {
                    accessory.ServiceStationReference.Load();
                }
                model.CHPrice = accessory.CBPrice.HasValue? accessory.CBPrice.Value.ToString() : "";
                model.Class = accessory.AccessoryClass.Name;
                model.Count = accessory.Count.ToString();
                model.Description = accessory.Description;
                model.ID = accessory.ID.ToString();
                model.MaterialNO = accessory.MaterialNO;
                model.ModelNO = accessory.ModelNO;
                model.Price = accessory.Price.HasValue? accessory.Price.Value.ToString():"";
                model.Station = accessory.ServiceStation.Name;
                model.UseTimes = accessory.UseTimes.HasValue? accessory.UseTimes.Value.ToString() : "0";

                //添加库存金额、消耗金额、消耗平台、消耗维修单号
                model.StockPriceSum = accessory.Price.HasValue ? (accessory.Count * accessory.Price).Value.ToString() : "0";
                model.ConsumedPriceSum = accessory.Price.HasValue ? ((accessory.UseTimes.HasValue? accessory.UseTimes.Value : 0) * accessory.Price).Value.ToString() : "0";

                model.ConsumedStation = accessory.ConsumedStation;
                model.ConsumedRMAID = accessory.ConsumedRMAID;

                models.Add(model);
            }

            return models;
        }

        public List<AccessoryTJModel> GetAccessoryTJBy(string modelNo, int classID, int stationID, int year, int month, int endYear, int endMonth)
        {
            List<AccessoryTJModel> models = new List<AccessoryTJModel>();
            IQueryable<Accessory> accessorys = GetEntities<Accessory>().OrderBy(a=>a.AccessoryClass.Name);
            if (stationID > 0)
            {
                accessorys = accessorys.Where(a => a.ServiceStation.ID == stationID);
            }
            if (classID > 0)
            {
                accessorys = accessorys.Where(a => a.AccessoryClass.ID == classID);
            }

            if (!string.IsNullOrEmpty(modelNo))
            {
                accessorys = accessorys.Where(a => a.ModelNO.Contains(modelNo));
            }
            
            foreach (Accessory sory in accessorys)
            {
                if(!sory.AccessoryClassReference.IsLoaded)
                {
                    sory.AccessoryClassReference.Load();
                }
                AccessoryTJModel model = new AccessoryTJModel();
                model.Class = sory.AccessoryClass.Name;
                model.Count = sory.Count;
                model.Description = sory.Description;
                model.ModelNO = sory.ModelNO;
                //int? usetimes = GetEntities<AccessoryRecord>(a => a.ServiceStation.ID == stationID
                //    && a.UseDate.Value.Year == year && a.UseDate.Value.Month == month
                //    && a.OperationType.Equals("消耗") && a.ModelNumber == sory.ModelNO).Sum(a => a.UseCount);
                int? usetimes = GetUsedTimesOfAccessory(sory.ModelNO, stationID, year, month, endYear, endMonth);
                model.TotalCHPrice = (sory.Count * sory.CBPrice).ToString();
                model.UseTimes = usetimes.HasValue?usetimes.Value:0;

                model.TotalUsePrice = (model.UseTimes * sory.CBPrice).ToString();
                model.TotalEarnPrice = (model.UseTimes * sory.Price).ToString();
                models.Add(model);
            }

            return models;
        }

        public int GetUsedTimesOfAccessory(string modelNO, int stationID, int year, int month, int endYear, int endMonth)
        {
            int usedTimes = 0;
            IQueryable<AccessoryRecord> resords = GetEntities<AccessoryRecord>().Where(a => a.ModelNumber.Equals(modelNO) && a.OperationType.Equals("维修使用"));
            
            if (stationID > 0)
            {
                resords = resords.Where(a=>a.ServiceStation.ID == stationID);
            }
            DateTime startDate = new DateTime(year, month, 1);
            if (endMonth == 12)
            {
                endYear += 1;
                endMonth = 1;
            }
            else
            {
                endMonth += 1;
            }
            DateTime endDate = new DateTime(endYear, endMonth, 1);
            foreach (AccessoryRecord record in resords)
            {
                if (record.EnterDate.HasValue && record.UseCount.HasValue 
                    && record.EnterDate.Value >= startDate 
                    && record.EnterDate.Value < endDate)
                {
                    usedTimes += record.UseCount.Value;
                }
            }
            return usedTimes;
        }

        public void UpdateAccessoryUsedCount()
        {
            List<QuatationForm> quatationForms = GetEntities<QuatationForm>().Where(q => !q.CalculateAccessoryUsedCount.HasValue).ToList();
            foreach (QuatationForm quatationForm in quatationForms)
            {
                if (!quatationForm.ApplicationProductReference.IsLoaded)
                {
                    quatationForm.ApplicationProductReference.Load();
                }
                if (!quatationForm.ApplicationProduct.ApplicationFormReference.IsLoaded)
                {
                    quatationForm.ApplicationProduct.ApplicationFormReference.Load();
                }
                if (!quatationForm.ApplicationProduct.ApplicationForm.ServiceStationReference.IsLoaded)
                {
                    quatationForm.ApplicationProduct.ApplicationForm.ServiceStationReference.Load();
                }

                if (quatationForm.ApplicationProduct.IsDecideToRepair.HasValue && 
                    quatationForm.ApplicationProduct.IsDecideToRepair.Value == true)
                {
                    List<Accessory> accessoryEntitys = GetEntities<Accessory>().Where(a => a.ModelNO == quatationForm.AccessoryName).ToList();
                    Accessory accessoryEntity = null;
                    foreach(Accessory accessory in accessoryEntitys)
                    {
                        if (!accessory.ServiceStationReference.IsLoaded)
                        {
                            accessory.ServiceStationReference.Load();
                        }

                        if (quatationForm.ApplicationProduct.UpgradeForm.Count() == 0 && 
                            quatationForm.ApplicationProduct.ApplicationForm.ServiceStation == accessory.ServiceStation)
                        {
                            accessoryEntity = accessory; 
                            break;
                        }
                        else if (quatationForm.ApplicationProduct.UpgradeForm.Count() > 0 &&
                            !quatationForm.ApplicationProduct.UpgradeForm.FirstOrDefault().Status.Equals("升级-不同意") &&
                            accessory.ServiceStation.ID == 1)
                        {
                            accessoryEntity = accessory;
                            break;
                        }
                        else if (quatationForm.ApplicationProduct.UpgradeForm.Count() > 0 &&
                          quatationForm.ApplicationProduct.UpgradeForm.FirstOrDefault().Status.Equals("升级-不同意") &&
                          accessory.ServiceStation == quatationForm.ApplicationProduct.ApplicationForm.ServiceStation)
                        {
                            accessoryEntity = accessory;
                            break;
                        }
                    }
                    if (accessoryEntity != null)
                    {
                        if (!accessoryEntity.UseTimes.HasValue)
                        {
                            accessoryEntity.UseTimes = 0;
                        }
                        accessoryEntity.UseTimes += quatationForm.Count;

                        // 添加消耗平台和消耗维修单号记录
                        if (string.IsNullOrEmpty(accessoryEntity.ConsumedStation))
                        {
                            accessoryEntity.ConsumedStation = quatationForm.ApplicationProduct.ApplicationForm.ServiceStation.Name + ":1;";
                        }
                        else
                        {
                            string[] stations = accessoryEntity.ConsumedStation.Split(new string[]{":",";"}, 60 , StringSplitOptions.RemoveEmptyEntries);
                            int i = 0;
                            for (; i < stations.Length-1; i = i + 2)
                            {
                                if (stations[i].Trim().Equals(quatationForm.ApplicationProduct.ApplicationForm.ServiceStation.Name))
                                {
                                    stations[i] = stations[i].Trim();
                                    stations[i + 1] = Convert.ToString(Convert.ToInt32(stations[i + 1]) + 1);
                                    break;
                                }
                            }
                            
                            if (i >= stations.Length - 1)
                            {
                                accessoryEntity.ConsumedStation += quatationForm.ApplicationProduct.ApplicationForm.ServiceStation.Name + ":1;";
                            }
                            else
                            {
                                accessoryEntity.ConsumedStation = "";
                                for (int j = 0; j < stations.Length - 1; j += 2)
                                {
                                    accessoryEntity.ConsumedStation += stations[j] + ":" + stations[j + 1] + ";";
                                }
                            }
                        }

                        if (string.IsNullOrEmpty(accessoryEntity.ConsumedRMAID))
                        {
                            accessoryEntity.ConsumedRMAID += quatationForm.ApplicationProduct.ApplicationForm.ApplicationCode + ":1;";
                        }
                        else
                        {
                        
                            string[] RMAs = accessoryEntity.ConsumedRMAID.Split(new string[] { ":", ";" }, 60, StringSplitOptions.RemoveEmptyEntries);
                            int i = 0;
                            for (; i < RMAs.Length - 1; i = i + 2)
                            {
                                if (RMAs[i].Trim().Equals(quatationForm.ApplicationProduct.ApplicationForm.ApplicationCode))
                                {
                                    try
                                    {
                                        RMAs[i] = RMAs[i].Trim();
                                        if (RMAs[i + 1].EndsWith(";"))
                                        {
                                            RMAs[i + 1] = RMAs[i + 1].Replace(";", "");
                                        }
                                        RMAs[i + 1] = Convert.ToString(Convert.ToInt32(RMAs[i + 1]) + 1);
                                        Console.WriteLine(string.Format("零件{0}:{1} 当前使用次数为:{2}", accessoryEntity.ID, accessoryEntity.ModelNO, RMAs[i + 1]));
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(string.Format("零件{0}:{1} 计算使用次数出错:{2}", accessoryEntity.ID, accessoryEntity.ModelNO, ex.ToString())); ;
                                    }
                                    break;
                                }
                            }

                            if (i >= RMAs.Length - 1)
                            {
                                accessoryEntity.ConsumedRMAID += quatationForm.ApplicationProduct.ApplicationForm.ApplicationCode + ":1;";
                            }
                            else
                            {
                                accessoryEntity.ConsumedRMAID = "";
                                for (int j = 0; j < RMAs.Length - 1; j += 2)
                                {
                                    accessoryEntity.ConsumedRMAID += RMAs[j] + ":" + RMAs[j + 1] + ";";
                                }
                            }

                            
                        }

                        UpdateEntity(accessoryEntity);
                    }
                    quatationForm.CalculateAccessoryUsedCount = true;

                    UpdateEntity(quatationForm);
                }
            }
        }

        public void UpdateAccessoryModelNO(string originalModelNO, string newModelNO)
        {
            ChangeLogService logService = new ChangeLogService();
            List<Accessory> accessoryEntities = GetEntities<Accessory>().Where(a => a.ModelNO.Equals(originalModelNO)).ToList();
            foreach (Accessory accessoryEntity in accessoryEntities)
            {
                accessoryEntity.ModelNO = newModelNO;
                UpdateEntity(accessoryEntity);

                string changeContent = string.Format("UpdateAccessoryModelNO ModelNO {0}->{1}", originalModelNO, newModelNO);
                logService.AddChangeLog(ChangeLogType.Accessory, accessoryEntity.ID.ToString(), changeContent);
            }            

            List<QuatationForm> quatationEntities = GetEntities<QuatationForm>().Where(q => q.AccessoryName.Equals(originalModelNO)).ToList();
            foreach (QuatationForm quatationEntity in quatationEntities)
            {
                quatationEntity.AccessoryName = newModelNO;
                UpdateEntity(quatationEntity);

                string changeContent = string.Format("UpdateAccessoryModelNO AccessoryName {0}->{1}", originalModelNO, newModelNO);
                logService.AddChangeLog(ChangeLogType.QuatationForm, quatationEntity.ID.ToString(), changeContent);
            }
        }

        public void DeleteAccessory(string id)
        {
            long idi = Convert.ToInt64(id);
            DeleteEntities<Accessory>(a => a.ID == idi, Guid.Empty);
            string changeContent = string.Format("DeleteAccessory");
            ChangeLogService service = new ChangeLogService();
            service.AddChangeLog(ChangeLogType.Accessory, id, changeContent);
        }
    }
}
